package com.yc.sole.erp.biz;

import cn.hutool.core.bean.BeanUtil;
import com.yc.sole.common.constant.PubConstant;
import com.yc.sole.erp.dto.OsOrderDto;
import com.yc.sole.erp.dto.SaleOrderDto;
import com.yc.sole.erp.dto.SupplierDto;
import com.yc.sole.erp.enums.OrderState;
import com.yc.sole.erp.exception.ErpResultEnum;
import com.yc.sole.erp.repository.OsOrderRepository;
import com.yc.sole.erp.repository.SaleOrderRepository;
import com.yc.sole.erp.repository.SupplierRepository;
import com.yc.sole.erp.request.OsOrderQueryReq;
import com.yc.sole.erp.request.OsOrderReq;
import com.yc.sole.erp.response.OsOrderResp;
import com.yc.sole.framework.exception.BaseException;
import com.yc.sole.framework.mybatis.page.Paging;
import com.yc.sole.framework.mybatis.util.PageUtil;
import com.yc.sole.system.service.SequenceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 服务接口实现
 *
 * @author yizuomin
 * @date 2024-03-13
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class OsOrderBiz {

    private final OsOrderRepository osOrderRepository;
    private final SaleOrderRepository saleOrderRepository;
    private final SupplierRepository supplierRepository;
    private final SequenceService sequenceService;

    /**
     * 新增外发订单
     *
     * @param req
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveOsOrder(OsOrderReq req) {
        // 查询订单
        SaleOrderDto saleOrderDto = saleOrderRepository.selectSaleOrderById(req.getOrderId());
        if (Objects.isNull(saleOrderDto)) {
            throw new BaseException(ErpResultEnum.SALE_ORDER_NOT_FOUND);
        }
        // 验证状态
        if (!OrderState.UN_HANDLE.equals(saleOrderDto.getOrderState())) {
            throw new BaseException(ErpResultEnum.ORDER_CAN_NOT_OUTSOURCING, saleOrderDto.getOrderState().getDescription());
        }
        // 查询供应商
        SupplierDto supplierDto = supplierRepository.selectSupplierById(req.getSupplierId());
        if (Objects.isNull(supplierDto)) {
            throw new BaseException(ErpResultEnum.SUPPLIER_NOT_FOUND);
        }
        // 修改订单状态为已外发
        SaleOrderDto updateOrderDto = new SaleOrderDto();
        updateOrderDto.setId(saleOrderDto.getId());
        updateOrderDto.setOrderState(OrderState.OUTSOURCED);
        saleOrderRepository.updateSaleOrderById(updateOrderDto);
        // 保存外发订单
        OsOrderDto osOrderDto = new OsOrderDto();
        String osOrderNo = sequenceService.generateSeqNo(PubConstant.OUTSOURCED_ORDER_SEQ_KEY);
        osOrderDto.setOsOrderNo(osOrderNo);
        osOrderDto.setDate(req.getDate());
        osOrderDto.setOrderId(saleOrderDto.getId());
        osOrderDto.setOrderNo(saleOrderDto.getOrderNo());
        osOrderDto.setSupplierId(supplierDto.getId());
        osOrderDto.setSupplierName(supplierDto.getSupplierName());
        osOrderDto.setUnitPrice(req.getUnitPrice());
        osOrderDto.setQuantity(req.getQuantity());
        // 利润 = （外发单价-订单单价） * 外发数量
        BigDecimal quantityDecimal = new BigDecimal(String.valueOf(req.getQuantity()));
        BigDecimal profit = (req.getUnitPrice().subtract(saleOrderDto.getUnitPrice())).multiply(quantityDecimal);
        osOrderDto.setProfit(profit);
        osOrderDto.setRemark(req.getRemark());
        osOrderDto.setCustomerId(saleOrderDto.getCustomerId());
        osOrderDto.setCustomerName(saleOrderDto.getCustomerName());
        osOrderDto.setProductId(saleOrderDto.getProductId());
        osOrderDto.setProductName(saleOrderDto.getProductName());
        osOrderDto.setOrderUnitPrice(saleOrderDto.getUnitPrice());
        // 总金额 = 外发单价 * 外发数量
        BigDecimal amount = req.getUnitPrice().multiply(quantityDecimal);
        osOrderDto.setAmount(amount);
        osOrderRepository.saveOsOrder(osOrderDto);
    }

    /**
     * 修改
     *
     * @param req
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateOsOrderById(OsOrderReq req) {
        // 查询外发订单
        OsOrderDto osOrderDto = osOrderRepository.selectOsOrderById(req.getId());
        if (Objects.isNull(osOrderDto)) {
            throw new BaseException(ErpResultEnum.OUTSOURCED_ORDER_NOT_FOUND);
        }
        // 查询供应商
        SupplierDto supplierDto = supplierRepository.selectSupplierById(req.getSupplierId());
        if (Objects.isNull(supplierDto)) {
            throw new BaseException(ErpResultEnum.SUPPLIER_NOT_FOUND);
        }
        // 只能修改供应商、备注、外发单价、日期
        OsOrderDto dto = new OsOrderDto();
        dto.setId(osOrderDto.getId());
        dto.setDate(req.getDate());
        dto.setSupplierId(supplierDto.getId());
        dto.setSupplierName(supplierDto.getSupplierName());
        dto.setUnitPrice(req.getUnitPrice());
        // 利润 = （外发单价-订单单价） * 外发数量
        BigDecimal quantityDecimal = new BigDecimal(String.valueOf(osOrderDto.getQuantity()));
        BigDecimal profit = (req.getUnitPrice().subtract(osOrderDto.getOrderUnitPrice())).multiply(quantityDecimal);
        dto.setProfit(profit);
        dto.setRemark(req.getRemark());
        // 总金额 = 外发单价 * 外发数量
        BigDecimal amount = req.getUnitPrice().multiply(quantityDecimal);
        dto.setAmount(amount);
        osOrderRepository.updateOsOrderById(dto);
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteOsOrderByIds(Set<Long> ids) {
        // 查询外发订单
        List<OsOrderDto> osOrderDtoList = osOrderRepository.selectOsOrderByIds(ids);
        for (OsOrderDto osOrderDto : osOrderDtoList) {
            //将订单状态由 已外发->待处理
            SaleOrderDto updateSaleOrderDto = new SaleOrderDto();
            updateSaleOrderDto.setId(osOrderDto.getOrderId());
            updateSaleOrderDto.setOrderState(OrderState.UN_HANDLE);
            saleOrderRepository.updateSaleOrderById(updateSaleOrderDto);
        }
        osOrderRepository.deleteOsOrderByIds(ids);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public OsOrderResp selectOsOrderById(Long id) {
        return BeanUtil.copyProperties(osOrderRepository.selectOsOrderById(id), OsOrderResp.class);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param queryReq
     * @return
     */
    public Paging<OsOrderResp> selectOsOrderPage(Paging<OsOrderQueryReq> page, OsOrderQueryReq queryReq) {
        Paging<OsOrderDto> paging = osOrderRepository.selectOsOrderPage(page, queryReq);
        return PageUtil.pageCopy(paging, OsOrderResp.class);
    }

    /**
     * 查询外发订单状态的数量
     *
     * @param queryReq
     * @return
     */
    /*public List<StateCountResp> selectOsOrderStateCount(OsOrderQueryReq queryReq) {
        List<StateCountResp> countRespList = osOrderRepository.selectOsOrderStateCount(queryReq);
        Long totalCount = countRespList.stream().map(StateCountResp::getCount).reduce(0L, Long::sum);
        ArrayList<StateCountResp> resultList = Lists.newArrayList(new StateCountResp("-1", "全部", totalCount));
        Map<String, StateCountResp> stateCountRespMap = countRespList.stream().collect(Collectors.toMap(StateCountResp::getState, v -> v));
        List<StateCountResp> respList = Arrays.stream(OsOrderState.values()).map(state -> {
            StateCountResp countResp = stateCountRespMap.get(state.getValue());
            if (Objects.isNull(countResp)) {
                countResp = new StateCountResp();
                countResp.setCount(0L);
            }
            countResp.setStateName(state.getDescription());
            countResp.setState(state.getValue());
            return countResp;
        }).toList();
        resultList.addAll(respList);
        return resultList;
    }*/

    /**
     * 取消外发订单
     *
     * @param id
     */
    /*@Transactional(rollbackFor = Exception.class)
    public void cancelOsOrder(Long id) {
        // 查询外发订单
        OsOrderDto osOrderDto = osOrderRepository.selectOsOrderById(id);
        if (Objects.isNull(osOrderDto)) {
            throw new BaseException(ErpResultEnum.OUTSOURCED_ORDER_NOT_FOUND);
        }
        //修改外发订单状态为已取消
        OsOrderDto updateOsOrderDto = new OsOrderDto();
        updateOsOrderDto.setId(osOrderDto.getId());
        updateOsOrderDto.setOsOrderState(OsOrderState.CANCELED);
        osOrderRepository.updateOsOrderById(updateOsOrderDto);
        //将订单状态由 已外发->待处理
        SaleOrderDto updateSaleOrderDto = new SaleOrderDto();
        updateSaleOrderDto.setId(osOrderDto.getOrderId());
        updateSaleOrderDto.setOrderState(OrderState.UN_HANDLE);
        saleOrderRepository.updateSaleOrderById(updateSaleOrderDto);
    }*/

    /**
     * 完成外发订单
     *
     * @param ids
     */
    /*@Transactional(rollbackFor = Exception.class)
    public void completeOrder(Set<Long> ids) {
        // 查询外发订单
        List<OsOrderDto> osOrderDtoList = osOrderRepository.selectOsOrderByIds(ids);
        if (CollUtil.isEmpty(osOrderDtoList)) {
            throw new BaseException(ErpResultEnum.OUTSOURCED_ORDER_NOT_FOUND);
        }
        for (OsOrderDto osOrderDto : osOrderDtoList) {
            //修改外发订单状态为已完成
            OsOrderDto updateOsOrderDto = new OsOrderDto();
            updateOsOrderDto.setId(osOrderDto.getId());
            updateOsOrderDto.setOsOrderState(OsOrderState.COMPLETED);
            osOrderRepository.updateOsOrderById(updateOsOrderDto);
            //将订单状态由 已外发->处理中
            SaleOrderDto updateSaleOrderDto = new SaleOrderDto();
            updateSaleOrderDto.setId(osOrderDto.getOrderId());
            updateSaleOrderDto.setOrderState(OrderState.PROCESSING);
            saleOrderRepository.updateSaleOrderById(updateSaleOrderDto);
        }
    }*/
}
